<template>
  <div>
    <!-- 登录页 2018/2/20 22:52 zhangQ -->
    <div>
      <div class="login-container"
           style="padding-bottom: 50px ;background-repeat: no-repeat;background-size: cover; margin-top: -60px;"
           :style="{'background-image':'url('+loginBg +')'}">

        <div class="loginDiv">
          <div class="loginTitle"><h4>登录联运e达</h4></div>
          <div class="formDiv">
            <!-- 表单start  -->
            <Form ref="loginForm" autoComplete="on" :model="loginForm" :rules="loginRules" class="card-box login-form">
              <Form-item prop="username" :class="userError">
                <!--<i-input type="text" v-model="loginForm.username" placeholder="用户名" autoComplete="on">-->
                <!--<Icon type="ios-person-outline" slot="prepend"></Icon>-->
                <!--</i-input>-->
                <input class="loginInput" type="text" v-model="loginForm.username" placeholder="用户名/企业名称"
                       autoComplete="on" tabindex="1" v-on:focus="inputUserFocus">
                <div class="loginIconDiv">
                  <i class="loginIcon userIcon"></i>
                </div>
                <div class="clearInput" v-show="showclearU" @click="clearU">
                  <Icon type="close-circled" size="16"></Icon>
                </div>
              </Form-item>
              <Form-item prop="password" :class="pwdError">
                <input class="loginInput" type="password" v-model="loginForm.password" placeholder="密码"
                       @keyup.enter="handleLogin" tabindex="2" v-on:focus="inputPwdFocus"
                       @keyup="detectCapsLock($event)">
                <div class="loginIconDiv">
                  <i class="loginIcon pwdIcon"></i>
                </div>
                <div class="clearInput" v-show="showclearP" @click="clearP">
                  <Icon type="close-circled" size="16"></Icon>
                </div>
              </Form-item>
              <div class="loginOther">
                <div class="checkRemmber">
                  <input type="checkbox" id="checkR" class="regular-checkbox" v-model="checkedR"/><label
                  for="checkR"><span></span>记住我</label>
                </div>
                <div class="findPwd">
                  <a href="#/user/findpassword">忘记密码？</a>
                </div>
              </div>
              <div class="showJY" v-show="showJY">
                <div class="JYTitle">
                  <Icon type="android-alert" color="#E41B33" size="18"></Icon>
                  <span>请点击下方按钮进行验证</span>
                </div>
                <div id="captcha">
                  <p id="wait">正在加载验证码......</p>
                  <div id="jyDiv"></div>
                </div>
              </div>
              <div class="showErrorM" v-show="showErrorM">
                <Icon type="android-alert" color="#E41B33" size="18"></Icon>
                <span>{{showErrorW}}</span>
              </div>
              <Form-item class="loginButton">
                <Button type="primary" @click="handleLogin('loginForm')" long>登录</Button>
              </Form-item>
              <hr class="loginHr"/>
              <div class="noNumber">
                <p>没有账号？</p>
                <a href="#/user/reg">免费注册</a>
              </div>
              <div class="clear"></div>
            </Form>
            <!-- 表单end -->
            <div class="clear"></div>
          </div>
          <div class="clear"></div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
  import loginBg from '../../../../static/img/img_reg.png'
  import {getGtConf} from '@api/common/user'
  import moment from 'moment'
  import initGeetest from '@/vendor/initGeetest'
  import _ from 'lodash'

  export default {
    name: 'index',
    data () {
      let loginForm = {
        username: '',
        password: ''
      }
      let validateUsername = (rule, value, callback) => {
        this.showErrorW = ''
        // this.userError=!isValidateUsername(rule)?'inputTextError':''
        if (!value) {
          callback()
          this.userError = 'inputTextError'
        } else {
          callback()
          this.userError = ''
        }
      }
      let validatePass = (rule, value, callback) => {
        this.showErrorW = ''
        if (value.length < 6) {
          // callback(new Error('密码不能小于6位'));
          callback()
          this.pwdError = 'inputTextError'
        } else {
          callback()
          this.pwdError = ''
        }
      }
      let loginRules = {
        username: [{
          required: true,
          trigger: 'blur',
          validator: validateUsername
        }],
        password: [{
          required: true,
          trigger: 'blur',
          validator: validatePass
        }]
      }
      let showErrorW = ''
      let showclearU = false
      let showclearP = false
      let checkedR = false
      let showDialog = false
      let jySuccess = true
      let showJY = false
      let showErrorM = false
      let submitForm = false
      let userError = ''
      let resetJY = false
      let pwdError = ''
      let datas = {
        loginBg,
        loginForm,
        loginRules,
        showErrorW,
        showclearU,
        showclearP,
        checkedR,
        showDialog,
        jySuccess,
        showJY,
        showErrorM,
        submitForm,
        userError,
        resetJY,
        pwdError
      }
      return datas
    },
    // watch: {
    //   // 如果路由有变化，会再次执行该方法
    //   '$route': 'fetchData'
    // },
    methods: {
      clearU () {
        this.loginForm.username = ''
        this.showclearU = false
      },
      clearP () {
        this.loginForm.password = ''
        this.showclearP = false
      },
      detectCapsLock (event) {
        let e = event || window.event
        // let o = e.target || e.srcElement
        let keyCode = e.keyCode || e.which // 按键的keyCode
        let isShift = e.shiftKey || (+keyCode === 16) || false // shift键是否按住
        if (((keyCode >= 65 && keyCode <= 90) && !isShift) || ((keyCode >= 97 && keyCode <= 122) && isShift)) {
          $('.ivu-poptip-popper').show()
        } else {
          $('.ivu-poptip-popper').hide()
        }
      },
      handleLogin () {
        this.submitForm++
        if (this.submitForm >= 5) {
          this.showErrorM = false
          this.showErrorW = ''
          this.jySuccess = false
          this.showJY = true
          if (!$('#jyDiv').html()) {
            getGtConf().then((response) => {
              // 调用 initGeetest 进行初始化
              // 参数1：配置参数
              // 参数2：回调，回调的第一个参数验证码对象，之后可以使用它调用相应的接口
              let data = JSON.parse(response.data.data)
              initGeetest({
                // 以下 4 个配置参数为必须，不能缺少
                gt: data.gt,
                challenge: data.challenge,
                offline: !data.success, // 表示用户后台检测极验服务器是否宕机
                new_captcha: data.new_captcha, // 用于宕机时表示是新验证码的宕机
                product: 'float', // 产品形式，包括：float，popup
                width: '316px'
                // 更多配置参数说明请参见：http://docs.geetest.com/install/client/web-front/
              }, this.gretestHandler)
            }).catch((error) => {
              console.log(error)
            })
          } else {
            this.showErrorM = true
            this.showErrorW = '请先完成验证'
            return false
          }
        }
        if (this.jySuccess) {
          $('#jyDiv').html('')
          this.$refs.loginForm.validate(valid => {
            if (valid) {
              this.$store.dispatch('doLogin', this.loginForm).then(res => {
                console.log(res)
                if (res.data.isSuccess === 1) {
                  if (this.checkedR) {
                    let obj = {
                      'xlinkUN': this.loginForm.username,
                      'xlinkUP': this.loginForm.password,
                      'time': moment().format()
                    }
                    obj = JSON.stringify(obj)
                    localStorage.setItem('xlinkU', obj)
                    // localStorage.setItem("xlink",this.loginForm.password)
                  } else {
                    localStorage.removeItem('xlinkU')
                  }
                  let toUrl = '/'
                  let timeoutRoute = sessionStorage.getItem('timeout_route')
                  if (timeoutRoute !== null) {
                    // toUrl = timeoutRoute
                    toUrl = '/back_end'
                    sessionStorage.removeItem('timeout_route')
                  }
                  if (this.$route.name === 'login_board') {
                    toUrl = '/back_end'
                  }
                  let isContainerPlatform = _.find(res.data.data.role, (item) => {
                    return item === '箱平台'
                  })
                  // console.log(isContainerPlatform)
                  if (isContainerPlatform) {
                    // toUrl = '/container_platform'
                  }
                  this.$Message.success(res.data.res)
                  this.$router.push({path: toUrl})
                } else {
                  // this.$Message.error(res.data.res)
                  this.showErrorM = true
                  this.showErrorW = res.data.res
                }
              }).catch(err => {
                // this.$message.error(err);
                this.showErrorM = true
                this.showErrorW = err.data.res
              })
            } else {
              return false
            }
          })
        } else {
          return false
        }
      },
      gretestHandler (captchaObj) {
        captchaObj.appendTo('#jyDiv') // 同时插入三个input表单时，geetest_challenge, geetest_validate, geetest_seccode
        captchaObj.onReady(function () {
          $('#wait').hide()
        })
        $('#btn').click(function (e) {
          var result = captchaObj.getValidate()
          if (!result) {
            e.preventDefault()
            return alert('请完成验证')
          }
        })
        captchaObj.onSuccess(() => {
          this.jySuccess = true
          this.loginForm.username = ''
          this.loginForm.password = ''
          this.showJY = false
          this.submitForm = 0
          this.showErrorM = false
          this.showErrorW = ' '
        })
      },
      inputUserFocus () {
        this.userError = ''
        this.showErrorM = false
        this.showErrorW = ''
        this.showclearU = true
      },
      inputPwdFocus () {
        this.pwdError = ''
        this.showErrorM = false
        this.showErrorW = ''
        this.showclearP = true
      },
      afterQRScan () {
      }
    },
    mounted () {
      let hasU = localStorage.hasOwnProperty('xlinkU')
      if (hasU) {
        let obj = JSON.parse(localStorage.getItem('xlinkU'))
        let sjd = (moment() - moment(obj.time)) / 1000
        let sjdays = moment.duration({seconds: sjd}).days()
        console.log(sjdays)
        if (sjdays >= 10) {
          localStorage.removeItem('xlinkU')
        } else {
          this.loginForm.username = obj.xlinkUN
          this.loginForm.password = obj.xlinkUP
          this.checkedR = true
        }
      }
    }
  }
</script>

<style>
  .login-container a {
    color: #0078de;
  }

  #canvascontainer {
    position: absolute;
    top: 0px;
  }

  .wz-input-group-prepend {
    background-color: #141a48;
    border: 1px solid #2d8cf0;
    border-right: none;
    color: #2d8cf0;
  }
</style>

<style rel="stylesheet/scss" lang="scss" scoped>
  .layout {
    border: 1px solid #d7dde4;
    background: #ccc;
  }

  .layout-logo {
    width: 200px;
    height: 40px;
    background: url('../../../../static/img/logo_bg.png') no-repeat;
    border-radius: 3px;
    float: left;
    position: relative;
    top: 15px;
    left: 20px;
  }

  .layout-nav {
    width: 600px;
    margin: 0 auto;
    color: #fff !important;
  }

  .layout-assistant {
    width: 300px;
    margin: 0 auto;
    height: inherit;
  }

  .layout-breadcrumb {
    padding: 10px 15px 0;
  }

  .layout-content {
    min-height: 200px;
    margin: 15px;
    overflow: hidden;
    background: #fff;
    border-radius: 4px;
  }

  .layout-content-main {
    padding: 10px;
  }

  .layout-copy {
    text-align: center;
    padding: 10px 0 20px;
    color: #9ea7b4;
  }

  .tips {
    font-size: 14px;
    color: #ddd;
    margin-bottom: 5px;
  }

  .login-container {
    height: 100vh;
    background-color: #2d3a4b;
    input:-webkit-autofill {
      -webkit-box-shadow: 0 0 0 1000px #293444 inset !important;
      -webkit-text-fill-color: #fff !important;
    }
    input {
      background: transparent;
      border: 1px solid #2d8cf0;
      -webkit-appearance: none;
      border-radius: 3px;
      padding: 12px 5px 12px 15px;
      color: #000;
      height: 47px;
    }
    .el-input {
      display: inline-block;
      height: 47px;
      width: 85%;
    }
    .svg-container {
      padding: 6px 5px 6px 15px;
      color: #889aa4;
    }

    .title {
      font-size: 26px;
      font-weight: 400;
      color: #eeeeee;
      margin: 0 auto 40px;
      text-align: center;
      font-weight: bold;
    }

    .login-form {
      height: auto;
      width: 316px;
      margin: 30px auto;
    }

    .el-form-item {
      border: 1px solid rgba(255, 255, 255, 0.1);
      background: rgba(0, 0, 0, 0.1);
      border-radius: 5px;
      color: #454545;
    }

    .forget-pwd {
      color: #fff;
    }
  }

  .loginDiv {
    position: absolute;
    width: 380px;
    right: 200px;
    background: #fff;
    top: 120px;
    padding: 30px 30px 0 30px;
    min-height: 445px;
  }

  .loginDiv .loginTitle {
    font-size: 20px;
    color: #1B1E21;
    height: 28px;
    line-height: 28px;
  }

  .loginDiv .loginInput {
    width: 100%;
    border: 1px solid #e3e3e3;
    height: 40px;
    padding: 13px 40px 13px 50px;
  }

  .loginDiv .loginInput:focus {
    outline: none;
    border: 1px solid #FECA2E;
    background: #fff;
  }

  .loginIconDiv {
    position: absolute;
    height: 20px;
    line-height: 20px;
    width: 40px;
    top: 10px;
    left: 0;
    border-right: 1px solid #d8d8d8;
  }

  .clearInput {
    position: absolute;
    height: 40px;
    line-height: 40px;
    width: 40px;
    text-align: center;
    top: 0;
    right: 0;
  }

  .loginIcon {
    display: block;
    width: 18px;
    height: 18px;
    margin: 0 auto;
  }

  .userIcon {
    background: url('../../../../static/img/icon_user.png') no-repeat;
    background-size: cover;
  }

  .pwdIcon {
    background: url('../../../../static/img/icon_pwd.png') no-repeat;
    background-size: cover;
    width: 14px;
  }

  .pwdIconPoptip {
    position: absolute;
    left: 0;
    top: -20px;
  }

  .loginOther {
    margin-top: -6px;
    width: 100%;
    height: 20px;
    line-height: 20px;
  }

  .checkRemmber {
    float: left;
    height: 14px;
  }

  .findPwd {
    float: right;
    height: 20px;
  }

  label {
    display: inline;
  }

  .regular-checkbox {
    display: none;
  }

  .regular-checkbox + label {
    color: #666;
    font-size: 14px;
  }

  .regular-checkbox + label span {
    background-color: #fafafa;
    border: 1px solid #cacece;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05), inset 0px -15px 10px -12px rgba(0, 0, 0, 0.05);
    padding: 6px;
    border-radius: 3px;
    display: inline-block;
    position: relative;
    top: 2px;
    margin-right: 5px;
  }

  .regular-checkbox:checked + label span {
    background-color: #FECA2E;
    border: 1px solid #FECA2E;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05), inset 0px -15px 10px -12px rgba(0, 0, 0, 0.05), inset 15px 10px -12px rgba(255, 255, 255, 0.1);
    color: #99a1a7;
  }

  .regular-checkbox:checked + label span:after {
    content: '\2714';
    font-size: 12px;
    position: absolute;
    top: -3px;
    left: 2px;
    color: #AE8B1D;
  }

  .findPwd a {
    color: #666;
  }

  .findPwd a:hover {
    color: #FECA2E;
  }

  .loginButton {
    margin-top: 10px;
    margin-bottom: 30px;
  }

  .ivu-form-item-content .ivu-btn {
    font-size: 20px;
    background: #FECA2E;
    box-shadow: 0 2px 10px 0 rgba(255, 219, 89, 0.88);
    border: 1px solid #FECA2E;
    border-radius: 2px;
    color: #1B1E21;
  }

  .loginHr {
    border: none;
    height: 1px;
    background-color: #eee;
  }

  .noNumber {
    margin-top: 20px;
    width: 100%;
  }

  .noNumber p {
    font-size: 14px;
    color: #666;
  }

  .noNumber a {
    margin-top: 20px;
    display: block;
    height: 50px;
    line-height: 50px;
    width: 100%;
    text-align: center;
    background: #FFF3CF;
    border: 1px solid #D9C380;
    border-radius: 2px;
    font-size: 20px;
    color: #E4B017;
    letter-spacing: 0;
  }

  .inputTextError .loginInput {
    background: #FFF1F3;
    border: 1px solid #E41B33;
  }

  .showErrorM {
    height: 20px;
    width: 100%;
    line-height: 20px;
    margin-top: 10px;
  }

  .showErrorM span, .JYTitle span {
    color: #E41B33;
    font-size: 14px;
  }

  .formDiv {
    height: auto;
    width: 100%;
  }

  .clear {
    clear: both;
  }

  .showJY {
    margin-top: 5px;
  }
</style>
